#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function

from api import XinliFMApi
from model import SongList
from player import Player
from utils import get_songs_list_by_ids, format_time
from downloader import Downloader


def main():
    current_page = 1
    songList = SongList()
    xinliFMApi = XinliFMApi()
    downloader = Downloader()
    musicPlayer = Player(downloader)
    songList.add_songs(get_songs_list_by_ids(xinliFMApi.get_latest_list()))

    musicPlayer.play(songList.get_current_song())
    next_song = songList.get_next_song()
    downloader.add_task(next_song)

    while True:
        print("[p:pause, u:unpause, q:quit, n:next, b:prev]")
        op = raw_input("Please decide what to do: ")
        if op == 's':
            musicPlayer.stop()
        elif op == 'p':
            musicPlayer.pause()
        elif op == 'u':
            musicPlayer.unpause()
        elif op == 'q':
            musicPlayer.stop()
            break
        elif op == 'n':
            musicPlayer.stop()
            musicPlayer.play(next_song)
            songList.set_current_song(next_song.id)
            next_song = songList.get_next_song()
            downloader.add_task(next_song)
        elif op == 'b':
            musicPlayer.stop()
            prev_song = songList.get_prev_song()
            next_song = songList.get_current_song()
            musicPlayer.play(prev_song)
            songList.set_current_song(prev_song.id)
        elif op == 'f':
            next_list = xinliFMApi.get_next_list(current_page)
            songList.add_songs(get_songs_list_by_ids(next_list))
            current_page += 1
        elif op == 'l':
            for k, s in enumerate(songList.get_songs_list()):
                print("%d: %s - %s" % (k + 1, s.title, s.speak), end='\n')
        elif op == 't':
            musicPlayer.toggle()
        elif op == 'j':
            index = raw_input("Please input the song index: ")
            song = songList.get_song_by_index(int(index) - 1)
            if song:
                musicPlayer.stop()
                musicPlayer.play(song)
                songList.set_current_song(song.id)
                next_song = songList.get_next_song()
                downloader.add_task(next_song)
            else:
                print("Can not get song at %d" % index)


if __name__ == '__main__':
    main()
